package cn.tq365.type.mybatis;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import com.baidu.api.sem.sms.v2.ScheduleType;

/**
 * List<ScheduleType>与以逗号分割的字符串的相互转换处理类
 * 
 * @author lili
 * 
 */
@MappedTypes(value = { List.class })
@MappedJdbcTypes(JdbcType.NVARCHAR)
public class BdScheduleTypeListTypeHandler extends
		BaseTypeHandler<List<ScheduleType>> {
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i,
			List<ScheduleType> parameter, JdbcType jdbcType)
			throws SQLException {
		if (parameter instanceof List) {
			List<ScheduleType> param = (List<ScheduleType>) parameter;
			String pstr = "";
			for (ScheduleType value : param) {
				pstr = pstr + value.getWeekDay() + "_" + value.getStartHour()
						+ "_" + value.getEndHour() + ",";
			}
			if (!StringUtils.isBlank(pstr)) {
				ps.setString(i, pstr.substring(0, pstr.length() - 1));
			} else {
				ps.setNull(i, jdbcType.NVARCHAR.TYPE_CODE);
			}
		} else {
			throw new SQLException("参数类型错误，要求的参数类型为：List<ScheduleType>");
		}
	}

	public static void main(String[] args) {
		System.out.println(new Date().getTime());
	}

	@Override
	public List<ScheduleType> getNullableResult(ResultSet rs, String columnName)
			throws SQLException {
		String rstr = rs.getString(columnName);
		if (StringUtils.isBlank(rstr))
			return null;
		return getResult(rstr);
	}

	@Override
	public List<ScheduleType> getNullableResult(CallableStatement cs,
			int columnIndex) throws SQLException {
		String rstr = cs.getString(columnIndex);
		if (StringUtils.isBlank(rstr))
			return null;
		return getResult(rstr);
	}

	@Override
	public List<ScheduleType> getNullableResult(ResultSet rs, int columnIndex)
			throws SQLException {
		String rstr = rs.getString(columnIndex);
		if (StringUtils.isBlank(rstr))
			return null;
		return getResult(rstr);
	}

	/**
	 * 重组结果
	 * 
	 * @param rstr
	 * @return
	 */
	private List<ScheduleType> getResult(String rstr) {
		List<ScheduleType> list = new ArrayList<ScheduleType>();
		String[] rarr = rstr.split(",");
		String[] temp = null;
		for (String str : rarr) {
			ScheduleType sch = new ScheduleType();
			temp = str.split("_");
			sch.setWeekDay(Long.parseLong(temp[0]));
			sch.setStartHour(Integer.parseInt(temp[1]));
			sch.setEndHour(Integer.parseInt(temp[2]));
			list.add(sch);
		}
		return list;
	}

}
